using System.Collections.Generic;
using UnityEngine;

public class EnergyRefillDialog : MonoBehaviour
{
	public EnergyItemButton buttonPrefab;

	public UITable table;

	public UIScrollView view;

	public GameObject dialogGameObject;

	private List<EnergyItemButton> shopItems = new List<EnergyItemButton>();

	private bool isAligned;

	public static EnergyRefillDialog instance { get; protected set; }

	private void Awake()
	{
		instance = this;
	}

	private void OnDestroy()
	{
		instance = null;
	}

	public void ShowOwnedEnergyRefills(bool isPushedAlready = false)
	{
		List<StoreItemsConfig.StoreItem> ownedFoodItems = GetOwnedFoodItems();
		if (ownedFoodItems.Count == 0)
		{
			if (isPushedAlready)
			{
				OnCancel();
			}
			return;
		}
		for (int i = 0; i < ownedFoodItems.Count; i++)
		{
			if (i >= shopItems.Count)
			{
				EnergyItemButton component = NGUITools.AddChild(table.gameObject, buttonPrefab.gameObject).GetComponent<EnergyItemButton>();
				component.gameObject.name = GGFormat.IndexName(i);
				shopItems.Add(component);
			}
			InitialiseButton(shopItems[i], ownedFoodItems[i]);
		}
		for (int j = ownedFoodItems.Count; j < shopItems.Count; j++)
		{
			InitialiseButton(shopItems[j], null);
		}
		if (!isPushedAlready)
		{
			NavigationManager.instance.PushModal(dialogGameObject);
		}
		table.Reposition();
		isAligned = false;
	}

	private void InitialiseButton(EnergyItemButton button, StoreItemsConfig.StoreItem item)
	{
		button.gameObject.SetActive(item != null);
		if (item != null)
		{
			button.Init(item);
		}
	}

	private List<StoreItemsConfig.StoreItem> GetOwnedFoodItems()
	{
		List<StoreItemsConfig.StoreItem> list = new List<StoreItemsConfig.StoreItem>();
		List<StoreItemsConfig.StoreItem> itemsForType = StoreItemsConfig.instance.GetItemsForType(StoreItemsConfig.StoreItem.ItemType.Food, true);
		foreach (StoreItemsConfig.StoreItem item in itemsForType)
		{
			int numberOfItemsOwned = PlayerInventory.instance.GetNumberOfItemsOwned(item.name);
			for (int i = 0; i < numberOfItemsOwned; i++)
			{
				list.Add(item);
			}
		}
		return list;
	}

	public void OnCancel()
	{
		NavigationManager.instance.Pop(true);
	}

	private void Update()
	{
		if (!isAligned && shopItems.Count > 0)
		{
			UITools.AlignToTopOnScroll(shopItems[0].gameObject.GetComponent<UIWidget>(), view, -5f);
			isAligned = true;
		}
	}
}
